<template>
  <div class="main_box" style="padding: 10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.combineId ? '编辑产品组合库' : '新增产品组合库' }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item prop="combineType" label="产品组合类型">
            <el-select v-model="dataForm.combineType" placeholder="请选择产品组合类型" clearable @change="dataForm.alarmType = ''">
              <el-option v-for="item in combineTypeList" :value="item.value" :label="item.label" :key="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="notifyFlag" label="通知规则" v-if="dataForm.combineType === 1">
            <el-radio-group v-model="dataForm.notifyFlag" @input="dataForm.alarmType = ''">
              <el-radio :label="0">不通知（默认）</el-radio>
              <el-radio :label="1">通知紧急联系人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="alarmType" label="报警类型" clearable
            v-if="dataForm.combineType === 2 || (dataForm.notifyFlag === 1 && dataForm.combineType === 1)">
            <el-select v-model="dataForm.alarmType" palceholder="请选择报警类型">
              <el-option v-for="item in alarmTypeList" :key="item.value" :value="item.value"
                :label="item.label"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item prop="safetyType" label="安全设备类型" v-if="dataForm.combineType == 2">
            <el-select v-model="dataForm.safetyType" placeholder="请选择安全设备类型" clearable>
              <el-option
                v-for="item in safetyTypeList"
                :value="item.value"
                :label="item.label"
                :key="item.value">
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item prop="villageId" label="所属小区">
            <el-select v-model="dataForm.villageId" @focus="getVillageList" placeholder="请选择所属小区" clearable filterable>
              <el-option v-for="item in villageList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="combineName" label="产品组合名称">
            <el-input type="text" v-model="dataForm.combineName"></el-input>
          </el-form-item>

          <el-form-item prop="combineDesc" label="产品组合描述">
            <el-input type="textarea" v-model="dataForm.combineDesc"></el-input>
          </el-form-item>

          <el-form-item prop="requiredFlag" label="是否默认">
            <el-switch v-model="dataForm.defaultFlag" active-text="默认" inactive-text="非默认"> </el-switch>
          </el-form-item>

          <el-form-item prop="mainImg" label="产品组合图片">
            <upload-img class="upload-img" @uploadFileList="getFileUrl" folder="combineImg">
              <img v-if="dataForm.mainImg" width="100%" :src="dataForm.mainImg" alt="" />
              <div class="tip">
                <i class="el-icon-upload" v-if="!dataForm.mainImg"></i>
                <div v-if="!dataForm.mainImg" class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
              </div>
            </upload-img>
          </el-form-item>
          <el-form-item prop="remark" label="备注">
            <el-input type="textarea" v-model="dataForm.remark"></el-input>
          </el-form-item>
        </el-row>

        <div class="tit">
          <h2>关联信息</h2>
        </div>

        <el-row style="display: flex; justify-content: flex-end">
          <el-button size="small" type="success" @click="handleAddGroup"><i class="fa fa-plus" /> 增加产品</el-button>
        </el-row>
        <el-table :data="relatedInfoTable" style="width: 100%">
          <el-table-column label="商户名称" v-if="dataForm.combineId">
            <template slot-scope="scope">
              <el-input type="text" disabled v-model="scope.row.businessName" />
            </template>
          </el-table-column>
          <el-table-column label="产品名称" v-if="dataForm.combineId">
            <template slot-scope="scope">
              <el-input type="text" disabled v-model="scope.row.name" />
            </template>
          </el-table-column>
          <el-table-column label="产品编号">
            <template slot-scope="scope">
              <el-input type="text" v-model="scope.row.goodsCode" />
            </template>
          </el-table-column>
          <el-table-column label="下单选项">
            <template slot-scope="scope">
              <el-select v-model="scope.row.selectedType">
                <el-option :value="1" label="下单时购买" />
                <el-option :value="2" label="下单后追加购买" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-if="relatedInfoTable.length !== 1" style="color: #eb6363"
                @click="handleDeleteGroup(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import CombineApi from '@/api/goods/combine';
import VillageApi from '@/api/address/village';
import UploadImg from '@/components/UploadImg';
import { EAlarmTypeList } from "@/enum";
export default {
  data() {
    return {
      dataForm: {
        combineId: '',
        combineName: '',
        combineType: '',
        villageId: '',
        safetyType: '',
        combineDesc: '',
        defaultFlag: false,
        mainImg: '',
        goodsCodes: '',
        alarmType: '',
        remark: '',
        notifyFlag: 0,
      },
      relatedInfoTable: [], //	关联信息表格
      alarmTypeList: EAlarmTypeList,
      combineTypeList: [
        { value: 1, label: '常规' },
        { value: 2, label: '安全报警' },
      ],
      safetyTypeList: [
        { value: 3, label: '烟雾报警器' },
        { value: 4, label: '燃气报警器' },
        { value: 5, label: '门磁报警器' },
        { value: 6, label: '水浸卫士' },
        { value: 8, label: 'SOS紧急呼叫' },
        { value: 9, label: '跌倒报警器' },
        { value: 10, label: '红外探测器' },
        { value: 15, label: '拐杖' },
        { value: 16, label: '胸牌' },
        { value: 17, label: '手表' },
      ],
      villageList: [],
      roleRules: {
        combineName: [{ required: true, message: '请输入产品组合名字', trigger: 'focus' }],
        combineType: [{ required: true, message: '请选择产品组合类型', trigger: 'change' }],
        villageId: [{ required: true, message: '请选择所属小区', trigger: 'change' }],
        mainImg: [{ required: true, message: '请上传产品组合图片', trigger: 'change' }],
      },
    };
  },
  components: {
    UploadImg,
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (this.$route.query.id) {
        this.dataForm.combineId = this.$route.query.id;
        this.getData();
      }
      // this.getVillageList()
    },
    keydown(e) {
      if (e.keyCode == 32) {
        e.returnValue = false;
      }
    },
    getVillageList() {
      if (this.flag) return;
      VillageApi.villageList({}).then((res) => {
        this.villageList = res.data;
        this.flag = true;
      });
    },
    getData() {
      CombineApi.getCombineInfo({
        id: this.dataForm.combineId,
      }).then((res) => {

        this.$Utils.bindingBean(this.dataForm, res.data);
        this.dataForm.defaultFlag = res.data.defaultFlag;
        this.villageList = [{ id: res.data.villageId, name: res.data.villageName }];
        if (res.data.goodsList) {
          this.relatedInfoTable = res.data.goodsList.map((c) => {
            return { goodsCode: c.goodsCode, selectedType: c.selectedType, businessName: c.businessName, name: c.name };
          });
        }
      });
    },
    getFileUrl(val) {
      if (val) {
        this.$Utils.notifySuccess('上传成功');
      }
      this.dataForm.mainImg = val[0];
    },
    sureClick() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
            if (this.relatedInfoTable.every((item) => item.goodsCode.trim() !== '')) {
              if (this.$route.query.isCopy) {
                this.dataForm.combineId = ""
              }
              if (this.dataForm.combineId) {
                this.editData();
              } else {
                this.addData();
              }
            } else {
              this.$message.error('关联信息列表中产品编号不可为空');
            }
          });
        }
      });
    },
    addData() {
      let param = {
        combineName: this.dataForm.combineName,
        combineDesc: this.dataForm.combineDesc,
        combineType: this.dataForm.combineType,
        safetyType: this.dataForm.safetyType,
        defaultFlag: this.dataForm.defaultFlag,
        villageId: this.dataForm.villageId,
        goodsCodes: this.dataForm.goodsCodes,
        mainImg: this.dataForm.mainImg,
        alarmType: this.dataForm.alarmType,
        remark: this.dataForm.remark,
        combineGoodsList: this.relatedInfoTable,
        notifyFlag: this.dataForm.combineType === 2 ? 1 : this.dataForm.notifyFlag,
      };

      CombineApi.addCombine(param).then((res) => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    editData() {
      let param = {
        combineId: this.dataForm.combineId,
        combineName: this.dataForm.combineName,
        combineDesc: this.dataForm.combineDesc,
        combineType: this.dataForm.combineType,
        safetyType: this.dataForm.safetyType,
        defaultFlag: this.dataForm.defaultFlag,
        villageId: this.dataForm.villageId,
        combineGoodsList: this.relatedInfoTable,
        mainImg: this.dataForm.mainImg,
        alarmType: this.dataForm.alarmType,
        remark: this.dataForm.remark,
        notifyFlag: this.dataForm.combineType === 2 ? 1 : this.dataForm.notifyFlag,
      };
      CombineApi.editCombine(param).then((data) => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },
    returnList() {
      this.$store.dispatch('delView', this.$route);
      this.$router.push({ path: '/goods/combineManagement' });
    },
    /**
     * 新增一组
     */
    handleAddGroup() {
      this.relatedInfoTable.push({ goodsCode: '', selectedType: 1 });
    },
    /**
     * 删除一组
     */
    handleDeleteGroup(index) {
      this.relatedInfoTable.splice(index, 1);
    },
  },
};
</script>

<style lang="scss" scoped>
@import '@/assets/css/views/add.scss';

.upload-img {
  &::v-deep .el-upload-dragger {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .tip {
      padding-bottom: 30px;
    }
  }
}</style>
